<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<view class="content detail">
			<!--商户池信息-->
			<view class="detail-item">
				<uni-section title="商户池信息" type="line"></uni-section>
				<view class="detail-content formRef">
					<uni-forms ref="formRef" :model="formData" :rules="formRules" labelWidth="80px">
					  <uni-forms-item label="区域" name="regionCode" required>
					    <uni-data-select
					    	v-model="formData.regionCode"
					    	placeholder="请选择区域"
					    	:localdata="setStore.allProvinceList"></uni-data-select>
					  </uni-forms-item>
						<uni-forms-item label="客户姓名" name="customerName" required>
					    <uni-easyinput v-model="formData.customerName" placeholder="请输入客户姓名" />
					  </uni-forms-item>
					  <uni-forms-item label="有无电话" required>
					    <view class="search-form-checkbox main-flex">
					    	<uni-data-checkbox @change="changeIsPhone" v-model="isPhone" :localdata="[{ value: 1, text: '有'},{ value: 0, text: '无'}]" />
					    </view>
					  </uni-forms-item>
					  <uni-forms-item label="联系电话" name="phone" required v-if="isPhone === 1">
					    <uni-easyinput @blur="blurPhone" maxlength="11" v-model="formData.phone" placeholder="请输入联系电话" />
					  </uni-forms-item>
					  <uni-forms-item label="客户等级" name="level">
					    <uni-data-select
					    	v-model="formData.level"
					    	placeholder="请选择客户等级"
					    	:localdata="customerClueLevelList"></uni-data-select>
					  </uni-forms-item>
					  <uni-forms-item label="门店名称" name="storeName" required>
					    <uni-easyinput v-model="formData.storeName" placeholder="请输入门店名称" />
					  </uni-forms-item>
					  <uni-forms-item label="门店地址" name="addr">
					    <uni-easyinput v-model="formData.addr" placeholder="请输入门店地址" />
					  </uni-forms-item>
					  <uni-forms-item label="地址详情" name="addrDetail">
					    <uni-easyinput v-model="formData.addrDetail" placeholder="请输入地址详情" />
					  </uni-forms-item>
					  <uni-forms-item label="门店照片" name="storeImag">
							<up-upload
								:fileList="fileList"
								@afterRead="afterRead"
								@delete="deletePic"
								name="1"
								multiple
								:maxCount="6"
								></up-upload>
					    <uni-easyinput style="display: none;" v-model="formData.storeImag" placeholder="请输入门店照片" />
					  </uni-forms-item>
						<!-- <uni-forms-item label="经度" name="lng">
						  <uni-easyinput v-model="formData.lng" placeholder="请输入经度">
								<template #right>
									<button size="mini" type="primary" class="input-right-btn" @click="getLocation">获取位置</button>
								</template>
							</uni-easyinput>
						</uni-forms-item>
						<uni-forms-item label="纬度" name="lat">
						  <uni-easyinput v-model="formData.lat" placeholder="请输入纬度" />
						</uni-forms-item> -->
					  <uni-forms-item label="是否公海" name="isPublic">
					    <view class="search-form-checkbox main-flex">
					    	<uni-data-checkbox v-model="formData.isPublic" :localdata="salesmanClueIsPublicList" />
					    </view>
					  </uni-forms-item>
					</uni-forms>
					<button type="primary" :disabled="isSubmit" :loading="isSubmit" @click="submit">提交</button>
				</view>
			</view>
		</view>
		<up-modal :show="showClue"  title="号码重复" @close="closeClue" @cancel="closeClue" @confirm="closeClue">
			<view class="slot-content">
				<view>手机号{{phoneClue?.phone}}已有商户池注册</view>
				<view>客户姓名：{{phoneClue?.customerName}}</view>
				<view>店铺名称：{{phoneClue?.storeName}}</view>
				<view>销售：{{phoneClue?.createName}}</view>
			</view>
		</up-modal>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref, watch, nextTick } from 'vue';
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import useUserStore from '@/store/modules/user'
import useSetStore from '@/store/modules/set'
import { timeFormat } from 'uview-plus'
import { salesmanClue, salesmanClueAdd, salesmanClueDetail, salesmanCluePhone } from "@/api/erp_api/sale"
import { customerClueLevel } from "@/api/system/dict/data"
import { allProvince } from "@/api/erp_api/region"
import { upload } from "@/api/system/common"
import { getUserLocation } from '@/utils/ty.js';
import { salesmanClueStatusList, salesmanClueIsPublicList } from '@/utils/config.js'

	const userStore = useUserStore()
	const setStore = useSetStore()
	const id = ref('')
	onLoad(async (option) => {
		await getCustomerClueLevel()
		if (option.id) {
			uni.setNavigationBarTitle({
				title: '修改商户池'
			})
			id.value = option.id
			getDetail()
		} else {
			getLocation()
		}
	})
	
	// 线索等级
	const customerClueLevelList = ref([])
	const getCustomerClueLevel = () => {
		return customerClueLevel().then(res => {
			customerClueLevelList.value = res.data.map(item => {
				return {
					...item,
					value: item.dictValue,
					text: item.dictLabel
				}
			}) || []
		})
	}
	
	// 获取详情
	const info = ref({})
	const isLoading = ref(false)
	const getDetail = () => {
		const params = {
			id: id.value
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		salesmanClueDetail(params).then(res => {
			info.value = res.data || {}
			formData.value = {
				customerName: res.data.customerName,
				phone: res.data.phone,
				regionCode: res.data.regionCode,
				storeName: res.data.storeName,
				storeImag: res.data.storeImag,
				addr: res.data.addr,
				addrDetail: res.data.addrDetail,
				level: res.data.level,
				lng: res.data.lng,
				lat: res.data.lat,
				isPublic: res.data.isPublic
			}
			fileList.value = res.data.storeImag ? res.data.storeImag.split(',').map(item => {
				return {
					status: 'success',
					message: '上传成功',
					url: item,
					type: 'image'
				}
			}) : []
			isLoading.value = false
			uni.hideLoading()
	  }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 图片上传
	const fileList = ref([])
	
	// 删除图片
	const deletePic = (event) => {
	  fileList.value.splice(event.index, 1)
		formData.value.storeImag = fileList.value.map(item => item.url).join(',')
	}
	
	// 新增图片
	const afterRead = async (event) => {
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file)
	  let fileListLen = fileList.value.length
	  lists.map((item) => {
	    fileList.value.push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	  for (let i = 0; i < lists.length; i++) {
	    const result = await upload(lists[i].url)
			const data = JSON.parse(result.data)
	    let item = fileList.value[fileListLen]
	    fileList.value.splice(fileListLen, 1, {
	      ...item,
	      status: 'success',
	      message: '',
	      url: data.url,
	    });
	    fileListLen++;
	  }
		formData.value.storeImag = fileList.value.map(item => item.url).join(',')
	};
	
	
	// 获取位置
	const isLocation = ref(false)
	const getLocation = () => {
		isLocation.value = true
		getUserLocation().then(res => {
			isLocation.value = false
			formData.value.lat = res.latitude
			formData.value.lng = res.longitude
			formData.value.addr = res.formatted_address
			formData.value.addrDetail = res.formatted_address
			// modal.showToast('位置获取成功')
		}).catch(err => {
			isLocation.value = false
			modal.showToast(err)
		})
	}
	
	// form表单数据
	const formData = ref({
		customerName: '',
		phone: '',
		regionCode: '',
		storeName: '',
		storeImag: '',
		addr: '',
		addrDetail: '',
		level: '',
		lng: '',
		lat: '',
		isPublic: 0
	})
	const formRef = ref(null)
	const formRules = ref({
		regionCode: {
			rules: [{ required: true, errorMessage: '请选择区域' }]
		},
		customerName: {
			rules: [{ required: true, errorMessage: '请输入客户姓名' }]
		},
		storeName: {
			rules: [{ required: true, errorMessage: '请输入门店名称' }]
		},
		phone: {
			rules: [{ required: true, errorMessage: '请输入联系电话' }]
		}
	})
	
	const isPhone = ref(1)
	const changeIsPhone = (e) => {
		formData.value.phone = ''
		isPhone.value = e.detail.value
	}
	
	const showClue = ref(false)
	const phoneClue = ref({})
	const blurPhone = async (e) => {
		if (e.detail.value && e.detail.value != '18888888888') {
			const resData = await getPhoneClue(e.detail.value)
			if (resData.length > 0) {
				showClue.value = true
				phoneClue.value = resData[0]
			}
		}
	}
	const getPhoneClue = (phone) => {
		return new Promise((resolve, reject) => {
			salesmanCluePhone(phone.replace(/\s/g, "")).then(res => {
				if (res?.data) {
					resolve(res.data)
				} else {
					reject(res?.code || '接口错误')
				}
			}).catch(err => {
				reject(err)
			})
		})
	}
	const closeClue = () => {
		showClue.value = false
	}
	
	const isSubmit = ref(false)
	// 提交
	const submit = () => {
		formRef.value.validate().then(async formRes => {
			const params = { ...formRes }
			if (id.value) {
				params.id = id.value
			}
			if (fileList.value.length < 3) {
				return uni.$u.toast('图片不能少于3张')
			}
			if (formData.value.lat) {
				params.lat = formData.value.lat
			}
			if (formData.value.lng) {
				params.lng = formData.value.lng
			}
			if (!isPhone.value) {
				params.phone = '18888888888'
			}
			if (params.phone != '18888888888') {
				const resData = await getPhoneClue(params.phone)
				if (resData.length > 0) {
					showClue.value = true
					phoneClue.value = resData[0]
					return false
				}
			}
			isSubmit.value = true
			salesmanClueAdd(params).then(async (res) => {
				modal.showToast(res.msg)
				await uni.$u.sleep(1000)
				isSubmit.value = false
				clear()
				uni.$emit('refreshList');  // 触发刷新事件
				uni.navigateBack({
					delta: 1
				})
			})
		})
	}
	// 清空
	const clear = () => {
		formData.value = {
			customerName: '',
			phone: '',
			regionCode: '',
			storeName: '',
			storeImag: '',
			addr: '',
			addrDetail: '',
			level: '',
			lng: '',
			lat: '',
			isPublic: 0
		}
	}
	watch(() => userStore.regionCode, (nval, oval) => {
		formData.value.regionCode = nval
	}, {
		immediate: true
	})
</script>

<style scoped lang="scss">
	
</style>
